<template>
  <div class="app-container">
    <!-- 查询表单 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="auto">
      <el-form-item label="预约人姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入"
          clearable
          @keyup.enter="handleQuery"
          style="width: 100px;"
        />
      </el-form-item>
      <el-form-item label="预约人手机号" prop="mobile">
        <el-input
          v-model="queryParams.mobile"
          placeholder="请输入预约人手机号"
          clearable
          @keyup.enter="handleQuery"
          style="width: 150px;"
        />
      </el-form-item>
      <el-form-item label="预约时间" prop="time">
        <el-date-picker
          v-model="queryParams.time"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择预约时间"
          clearable
          style="width: 140px;"
        />
      </el-form-item>

      <el-form-item label="预约类型" prop="type">
        <el-select v-model="queryParams.type" clearable placeholder="请选择" style="width: 110px">
          <el-option
            v-for="dict in nursing_reservation_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="预约状态" prop="status">
        <el-select v-model="queryParams.status" clearable placeholder="请选择" style="width: 100px">
          <el-option
            v-for="dict in nursing_reservation_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="reservationList" @selection-change="handleSelectionChange">
      <el-table-column label="序号" align="center" type="index" width="80px" />
      <el-table-column label="预约人姓名" align="center" prop="name" />
      <el-table-column label="预约人手机号" align="center" prop="mobile" />
      <el-table-column label="预约时间" align="center" prop="time" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.time, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="探访人" align="center" prop="visitor" />
      <el-table-column label="预约类型" align="center" prop="type">
        <template #default="scope">
          <el-tag :type="scope.row.type === 0 ? 'success' : 'primary'" effect="light">{{ scope.row.type === 0 ? '参观预约' :
            '探访预约' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="预约状态" align="center" prop="status" width="120">
        <template #default="scope">
          <el-tag :type="scope.row.status === 0 ? 'info' : scope.row.status === 1 ? 'success' : scope.row.status === 2 ? 'danger' : 'warning'" effect="light">
          {{ scope.row.status === 0 ? '待报道' : scope.row.status === 1 ? '已报道' : scope.row.status === 2 ? '已取消' : '已过期' }}
        </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Check"
            @click="handleReport(scope.row)"
            v-if="scope.row.status === 0"
          >报道</el-button>
          <el-button link type="warning" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 修改状态对话框 当我点击修改页面后框中显示的为1：待报道，而不是数字 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="reservationRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="预约状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择预约状态" style="width: 150px">
            <el-option label="待报道" :value="0" />
            <el-option label="已报道" :value="1" />
            <el-option label="已取消" :value="2" />
            <el-option label="已过期" :value="3" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Reservation">
import { ref, reactive, toRefs, getCurrentInstance } from 'vue'
import { listReservation, getReservation, delReservation, updateReservation } from '@/api/nursing/reservation'

// 获取实例
const { proxy } = getCurrentInstance()

// 响应式数据
const reservationList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref('')

// 数据模型
const data = reactive({
  form: { status: null }, // 初始化 status
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    mobile: null,
    time: null,
    visitor: null,
    type: null,
    status: null
  },
  rules: {
    status: [{ required: true, message: '请选择预约状态', trigger: 'change' }]
  }
})

const { queryParams, form, rules } = toRefs(data)

// 使用字典（替代硬编码）
const { nursing_reservation_type } = proxy.useDict('nursing_reservation_type')
const { nursing_reservation_status } = proxy.useDict('nursing_reservation_status')

// 根据状态返回 tag 类型
const getStatusTagType = (status) => {
  return status === 0 ? 'info' : status === 1 ? 'success' : status === 2 ? 'danger' : 'warning'
}

/** 查询列表 */
function getList() {
  loading.value = true
  listReservation(queryParams.value)
    .then(res => {
      reservationList.value = res.rows || []
      total.value = res.total
    })
    .finally(() => {
      loading.value = false
    })
}

/** 搜索 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置 */
function resetQuery() {
  proxy.resetForm('queryRef')
  handleQuery()
}

/** 重置表单 */
function reset() {
  form.value = { id: null, status: null }
  proxy.resetForm('reservationRef')
}

/** 取消 */
function cancel() {
  open.value = false
}

/** 修改 */
function handleUpdate(row) {
  reset()
  const id = row.id || ids.value[0]
  getReservation(id).then(({ data }) => {
    form.value = { ...data }
    open.value = true
    title.value = '修改预约信息'
  })
}

/** 报道 */
function handleReport(row) {
  handleUpdateStatus(row, 1, `确认预约人 "${row.name}" 已到现场？`, '报道成功')
}

/** 删除 */
function handleDelete(row) {
  const ids = [row.id].flat()
  proxy.$modal.confirm(`是否确认删除编号为 "${ids.join(',')}” 的数据？`).then(() => {
    return delReservation(ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess('删除成功')
  })
}

/** 提交表单 */
function submitForm() {
  proxy.$refs.reservationRef.validate(valid => {
    if (valid) {
      updateReservation(form.value).then(() => {
        proxy.$modal.msgSuccess('修改成功')
        open.value = false
        getList()
      })
    }
  })
}

// 通用状态更新方法
function handleUpdateStatus(row, status, confirmMsg, successMsg) {
  proxy.$modal.confirm(confirmMsg).then(() => {
    return updateReservation({ id: row.id, status })
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess(successMsg)
  })
}

// 初始化
getList()
</script>